<template>
  <div :class="className" :style="{ height: height, width: width }" />
</template>

<script>
var echarts = require('echarts/lib/echarts')
// 引入 ECharts 主模块
require('echarts/lib/chart/gauge')
// 引入提示框和标题组件
require('echarts/lib/component/tooltip')
require('echarts/lib/component/legend')
require('echarts/lib/component/dataZoom')
import { debounce } from '@/utils'
import { themeColor } from '@/assets/echarts/theme'

export default {
  name: 'GaugeChart',
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '100%'
    },
    data: {
      type: Array,
      default: () => ([])
    }
  },
  data() {
    return {
      chart: null
    }
  },
  computed: {
    lineData: function() {
      return this.data.map(v => v.yAxis)
    }
  },
  watch: {
    data: {
      handler() {
        this.initChart()
      }
    }
  },
  mounted() {
    this.initChart()
    this.__resizeHandler = debounce(() => {
      if (this.chart) {
        this.chart.resize()
      }
    }, 100)
    window.addEventListener('resize', this.__resizeHandler)
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    window.removeEventListener('resize', this.__resizeHandler)
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el, 'themeColor')
      this.chart.setOption({
        color: themeColor,
        tooltip: {
          formatter: '{a} <br/>{b} : {c}%'
        },
        toolbox: {
          feature: {
            restore: {},
            saveAsImage: {}
          }
        },
        series: [
          {
            name: '业务指标',
            type: 'gauge',
            axisLine: { // 坐标轴线
              lineStyle: { // 属性lineStyle控制线条样式
                width: 10
              }
            },
            splitLine: { // 分隔线
              length: 15, // 属性length控制线长
              lineStyle: { // 属性lineStyle（详见lineStyle）控制线条样式
                color: 'auto'
              }
            },
            detail: {
              formatter: '{value}小时',
              show: true,
              fontSize: 16,
              offsetCenter: [0, 50]
            },
            pointer: {
              length: '81%',
              width: 6
            },
            axisLabel: {
              show: false
            },
            data: [{ value: 50, name: '总OEE' }]
          }
        ]
      })
    }
  }
}
</script>
